import { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import { BaseRequestHttp,config } from "./helper/axios";
import {ResultEnum} from "@/enum/http";


/**
 * pinia 错误使用说明示例
 * https://github.com/vuejs/pinia/discussions/971
 * https://github.com/vuejs/pinia/discussions/664#discussioncomment-1329898
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#single-page-applications
 */
class RequestHttp extends BaseRequestHttp {
	public constructor(config: AxiosRequestConfig) {

		const response = (response: AxiosResponse,config:any) => {
			const { data } = response;
			if (data.code && data.code !== ResultEnum.SUCCESS) {
				return Promise.reject(data);
			}
			return data;
		}

		const asyncError = (error: AxiosError) => {
			const { response } = error;
			// 请求超时单独判断，因为请求超时没有 response
			if (error.message.indexOf("timeout") !== -1) console.error("请求超时！请您稍后重试");
			// 根据响应的错误状态码，做不同的处理
			// 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
			// if (!window.navigator.onLine) router.replace("/500");
			return Promise.reject(error);
		}
		// 实例化axios
		super(config, response, asyncError);
	}
}

export default new RequestHttp(config);